package com.engr.lyx.auth.biz.service.impl;

import com.engr.lyx.auth.biz.service.UserService;
import com.engr.lyx.base.client.req.UserReq;
import com.engr.lyx.common.http.OpenRestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.Map;

/**
 * @program blog
 * @description:
 * @author: LiuYanXin
 * @create: 2020-12-15 15:41
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private OpenRestTemplate restTemplate;

    @Autowired
    private ResourceServerProperties resourceServerProperties;

    @Override
    public Object login(UserReq userReq) {

        // 使用oauth2密码模式登录.
        MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
        postParameters.add("username", userReq.getUsername());
        postParameters.add("password", userReq.getPassword());
        postParameters.add("client_id", resourceServerProperties.getClientId());
        postParameters.add("client_secret", resourceServerProperties.getClientSecret());
        postParameters.add("grant_type", "password");
        postParameters.add("scope", "server");

        HttpHeaders headers = new HttpHeaders();
        // 使用客户端的请求头,发起请求
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 强制移除 原来的请求头,防止token失效
        headers.remove(HttpHeaders.AUTHORIZATION);
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity(postParameters, headers);
        Map result = restTemplate.postForObject("http://localhost:8080/auth/oauth/token", request, Map.class);
        return result;
    }

}
